package App.Repository;

import App.Model.Fee.*;
import App.Model.Project.CrmProjectMember;
import org.springframework.stereotype.Repository;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xw on 2020/3/10.
 */

@Repository
public class FeeRepository extends BaseRepository {


    //LawFee
    public GetLawFeeResponse GetLawFee(GetLawFeeRequest _request) {


        String _caseid = _request.getCaseid();
        float _requestMoney = _request.getMoney();
        float _money = _requestMoney;
        float _caculateMoneyMin = 0;
        float _caculateMoneyMax = 0;
        String _formula_min = "";
        String _formula_max = "";
        String _case_money = "";

        GetLawFeeResponse _response = new GetLawFeeResponse();


        String _strSql = " select * from crm_law_fee_formula where hasLimit = 1 and caseid=:caseid limit 1";

        Map<String, Object> _params = new HashMap<>();
        _params.put("caseid", _caseid);
        List<CrmLawFee> _lists = getEntitys(_strSql, _params, CrmLawFee.class);

        boolean _hasLimit = false;
        if (_lists != null && _lists.size() > 0) {
            _hasLimit = true;
        }

        //需要根据金额范围过滤
        if (_hasLimit == true) {
            _case_money = Float.toString(_requestMoney);

            //律师费 formula_type=1
            _strSql = " select * from crm_law_fee_formula " +
                    "where formula_type=1 and caseid=:caseid " +
                    "and haslimit=1 " +
                    "and  limit_left*10000.0<=:money and limit_right*10000.0>:money ";
            _params.clear();
            _params.put("caseid", _caseid);
            _params.put("money", _requestMoney);

            _lists = getEntitys(_strSql, _params, CrmLawFee.class);
            if (_lists != null && _lists.size() > 0) {
                CrmLawFee _theFee = _lists.get(0);

                float _param_a = _theFee.getParam_a();
                float _operator_min = _theFee.getOperator_min();
                float _operator_max = _theFee.getOperator_max();
                float _param_b_min = _theFee.getParam_b_min();
                float _param_b_max = _theFee.getParam_b_max();
                float _param_c = _theFee.getParam_c();

                String _param_a_str = Float.toString(_param_a);
                String _param_b_min_str = Float.toString(_param_b_min);
                String _param_b_max_str = Float.toString(_param_b_max);

                if (_operator_min == 0) {
                    _caculateMoneyMin = (_money * _param_a/100 - _param_b_min) * _param_c;
                    _formula_min = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "-" + _param_b_min_str + ")x" + _param_c;
                } else {
                    _caculateMoneyMin = (_money * _param_a/100 + _param_b_min) * _param_c;
                    _formula_min = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "+" + _param_b_min_str + ")x" + _param_c;
                }
                if (_operator_max == 0) {
                    _caculateMoneyMax = (_money * _param_a/100 - _param_b_max) * _param_c;
                    _formula_max = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "-" + _param_b_max_str + ")x" + _param_c;
                } else {
                    _caculateMoneyMax = (_money * _param_a/100 + _param_b_max) * _param_c;
                    _formula_max = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "+" + _param_b_max_str + ")x" + _param_c;
                }
            }
        } else {
            //不需要根据金额范围过滤
            _strSql = " select * from crm_law_fee_formula where caseid=:caseid and haslimit=2";
            _params.clear();
            _params.put("caseid", _caseid);
            _lists = getEntitys(_strSql, _params, CrmLawFee.class);
            CrmLawFee _theFee = _lists.get(0);

            if(_theFee != null){
                _caculateMoneyMin = _theFee.getParam_b_min();
                _caculateMoneyMax = _theFee.getParam_b_max();
                _case_money = _theFee.getRange_condition();
                _formula_min = "";
                _formula_max = "";
            }
        }

        _response.setFee_min(formatDouble(_caculateMoneyMin));
        _response.setFee_max(formatDouble(_caculateMoneyMax));
        _response.setFee_min_cut(formatDouble(_caculateMoneyMin/2.0));
        _response.setFee_max_cut(formatDouble(_caculateMoneyMax/2.0));
        _response.setFormula_min(_formula_min);
        _response.setFormula_max(_formula_max);
        _response.setCase_money(_case_money);

        //增加执行费用和合计费用 合计律师费=一审律师费+二审律师费+执行律师费  为区间值
        _response.setExecute_min_money(_response.getFee_min());
        _response.setExecute_max_money(_response.getFee_max());
        _response.setAmount_min_to_money(formatDouble(_caculateMoneyMin+_caculateMoneyMin/2.0+_caculateMoneyMin));
        _response.setAmount_max_to_money(formatDouble(_caculateMoneyMax+_caculateMoneyMax/2.0+_caculateMoneyMax));
        return _response;
    }

    public List<CrmCase> GetLawerCase(GetCaseRequest _requset) {

        int _casetype = _requset.getCasetype();
        String _strSql = " select * from crm_case where casetype=:casetype ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("casetype", _casetype);
        List<CrmCase> _lists = getEntitys(_strSql, _params, CrmCase.class);
        return _lists;
    }


    //获取诉讼费用
    public GetLitigationFeeResponse GetLitigationFee(GetLitigationFeeRequest _request, int userid) {

        GetLitigationFeeResponse _response = new GetLitigationFeeResponse();
        _response.setProcess_fee_remark("");
        _response.setSeal_money_remark("");
        _response.setSecurity_fee_remark("");
        _response.setSue_money_remark("");
        _response.setProcess_fee("");
        _response.setSecurity_fee("");

        String _caseid = _request.getCaseid();

        //起诉金额
        float sue_money_request = _request.getSue_money();
        float sue_money = sue_money_request;

        //查封金额
        float seal_money_request = _request.getSeal_money();
        float seal_money = seal_money_request;

        CrmCase _theCase = GetCaseInfo(_caseid);

        //保全费 formula_type=4
        String _strSql = " select * from crm_law_fee_formula where formula_type=4 and limit_left*10000.0<=:money and limit_right*10000.0>:money ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("money", seal_money_request);

        List<CrmLawFee> _lists = getEntitys(_strSql, _params, CrmLawFee.class);
        CrmLawFee _theFee;
        if(_lists != null && _lists.size() > 0) {
            _theFee = _lists.get(0);

            CaculateFeeItem _item = CaculateFee(seal_money, _theFee, _theCase);

            _response.setSecurity_fee(_item.getMoney());
            _response.setSecurity_fee_formula(_item.getFormula());
        }

        //受理费 formula_type=3
        //这里取limit 1主要是考虑X=0的时候
        _strSql = " select * from crm_law_fee_formula " +
                "where formula_type=3 and caseid=:caseid and haslimit=1 and  limit_left*10000.0<=:money and limit_right*10000.0>:money " +
                "order by limit_right  limit 1";
        _params.clear();
        _params.put("caseid", _caseid);
        _params.put("money", sue_money_request);

        if (_theCase.getCasetype() == 2 && _theCase.getFeetype() == 4) {
            _strSql = " select * from crm_law_fee_formula where caseid=:caseid and haslimit=2";
            _params.clear();
            _params.put("caseid", _caseid);
        }

        _lists = getEntitys(_strSql, _params, CrmLawFee.class);
        if(_lists != null && _lists.size() > 0){
            _theFee = _lists.get(0);
            CaculateFeeItem _item2 = CaculateFee(sue_money, _theFee, _theCase);

            _response.setProcess_fee(_item2.getMoney());
            _response.setProcess_fee_formla(_item2.getFormula());

//            String _conditon = _theFee.getRange_condition();
//            if (_conditon.equals("按件收取")) {
//                _response.setSue_money_remark("按件收取");
//                _response.setSeal_money_remark("请输入查封金额");
//            }

            if (_theCase.getCasetype() == 2 && _theCase.getFeetype() == 4) {
                _response.setProcess_fee(_item2.getFormula());
                _response.setProcess_fee_formla("");
            }
        }
        _response.setProcess_fee_remark("原告预交给法院，最后由败诉方返还或法院退费");
        _response.setSecurity_fee_remark("原告预交给法院，最后由败诉方返还");

        //申请执行 类型
        if (_caseid.equals("bf832079-6349-11ea-9ab4-000c29b9989b")) {
            _response.setProcess_fee_remark("被执行人向法院缴纳");
            _response.setSecurity_fee_remark("申请执行人预交给法院，最后由被执行人返还");
        }

        //增加保全担保费，会计预付费用=受理费+保全费+ 保全担保费
        Double securityGuaranteeFee=seal_money_request*0.003;
        if(securityGuaranteeFee<800)
            securityGuaranteeFee=800d;
        _response.setSecurity_guarantee_fee(securityGuaranteeFee+"");
        _response.setTotal_payment_fee((convertToDouble(_response.getProcess_fee())+convertToDouble(_response.getSecurity_fee())+securityGuaranteeFee)+"");
        _response.setSecurity_guarantee_remark(seal_money_request+"*0.003（保全担保费低于 800，按 800 显示）");
        return _response;
    }

    private CaculateFeeItem CaculateFee(float _money, CrmLawFee _theFee, CrmCase _theCase) {

        float _caculateMoneyMin = 0;
        String _formula_min = "";

        float _caculateMoneyMax = 0;
        String _formula_max = "";

        String _remark = "";

        float _param_a = _theFee.getParam_a();
        float _operator_min = _theFee.getOperator_min();
        float _operator_max = _theFee.getOperator_max();
        float _param_b_min = _theFee.getParam_b_min();
        float _param_b_max = _theFee.getParam_b_max();
        float _param_c = _theFee.getParam_c();
        float _param_d = _theFee.getParam_d();
        String _caseid = _theFee.getCaseid();


        String _param_a_str = Float.toString(_param_a);
        String _param_b_min_str = Float.toString(_param_b_min);
        String _param_b_max_str = Float.toString(_param_b_max);

        CaculateFeeItem _fee = new CaculateFeeItem();

        if (_operator_min == 0) { //减号
            _caculateMoneyMin = _money * _param_a/100 - _param_b_min;
            _formula_min = formatDouble(_money) + "x" + _param_a_str + "%" + "-" + _param_b_min_str + "";

            if (_param_d > 1) {
                _caculateMoneyMin = _caculateMoneyMin / _param_d;
                _formula_min = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "-" + _param_b_min_str + ")÷" + _param_d;
            }
        } else { //加号
            _caculateMoneyMin = _money * _param_a/100 + _param_b_min;
            _formula_min = formatDouble(_money) + "x" + _param_a_str + "%" + "+" + _param_b_min_str;

            if (_param_d > 1) {
                _caculateMoneyMin = _caculateMoneyMin / _param_d;
                _formula_min = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "+" + _param_b_min_str + ")÷" + _param_d;
            }
        }

        if (_operator_max == 0) {
            _caculateMoneyMax = (_money * _param_a/100 - _param_b_max) * _param_c;
            _formula_max = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "-" + _param_b_max_str + ")x" + _param_c;

            if (_param_d > 1) {
                _caculateMoneyMax = _caculateMoneyMax / _param_d;
                _formula_max = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "-" + _param_b_min_str + ")÷" + _param_d;
            }
        } else {
            _caculateMoneyMax = (_money * _param_a/100 + _param_b_max) * _param_c;
            _formula_max = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "+" + _param_b_max_str + ")x" + _param_c;

            if (_param_d > 1) {
                _caculateMoneyMax = _caculateMoneyMax / _param_d;
                _formula_max = "(" + formatDouble(_money) + "x" + _param_a_str + "%" + "+" + _param_b_min_str + ")÷" + _param_d;
            }
        }

//        if (_theCase.getCasetype() == 2 && _theCase.getFeetype() == 4) {
//            _formula_min = Float.toString(_param_b_min);
//
//            if (_param_b_max != 0) {
//                _formula_min += "-" + Float.toString(_param_b_max);
//
//            }
//        }

        if(_param_b_max > 0 && _caculateMoneyMax > 0){
            String val = String.format("%s-%s", _caculateMoneyMin, _caculateMoneyMax);
            _fee.setMoney(val);
            _fee.setFormula(val);
        }else{
            _fee.setMoney(formatDouble(_caculateMoneyMin));
            _fee.setFormula(_formula_min);
        }
        return _fee;

    }


    private CrmCase GetCaseInfo(String caseid) {

        String _strSql = " select * from crm_case where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", caseid);

        List<CrmCase> _lists = getEntitys(_strSql, _params, CrmCase.class);
        return _lists.get(0);

    }

    private static String formatDouble(double doubleValue) {
        DecimalFormat df = new DecimalFormat("#,##0.00");
        String strValue = df.format(doubleValue);

        return strValue;
    }
    public static double convertToDouble(String stringValue) {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setDecimalSeparatorAlwaysShown(false);
        decimalFormat.setGroupingSize(0);
        double value = 0.0d;
        if(!stringValue.equals("")){
            try {
                value = decimalFormat.parse(stringValue.replace(",", "")).doubleValue();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return value;
    }
}
